// src/store/tableStore.ts
import { create } from "zustand";
import { userApi } from "../api";
import { GetListParams } from "../api/types/user";

interface TableState {
  data: any[];
  loading: boolean;
  params: {
    page: number;
    page_size: number;
    start_t: number;
    end_t: number;
    channel: string;
    network: string;
    country: string;
  };
  setData: (data: any[]) => void;
  setParams: (params: Partial<TableState["params"]>) => void;
  fetchData: () => Promise<void>;
}

const useTableStore = create<TableState>((set, get) => ({
  data: [],
  loading: false,
  params: {
    page: 1,
    page_size: 20,
    start_t: 1743387861,
    end_t: 1743647061,
    channel: "",
    network: "",
    country: "",
  },

  setData: (data) => set({ data }),

  setParams: (params) => {
    set((state) => ({ params: { ...state.params, ...params } }));
    get().fetchData();
  },

  fetchData: async () => {
    try {
      set({ loading: true });
      const { params } = get();
      const res = await userApi.getNewList({
        ...(params as GetListParams & { admin_user_id: number }),
        // admin_user_id: 8,
        // sig: "3da8be048bd72145fd96fb0920643f53",
      });

      // 这里需要根据实际接口返回结构调整
      const mappedData = res.data.map((item: any) => ({
        key: item.id,
        name: item.name,
        age: item.age,
        address: item.address,
        tags: item.tags,
      }));

      set({ data: mappedData });
    } catch (error) {
      console.error("Fetch data error:", error);
    } finally {
      set({ loading: false });
    }
  },
}));

export default useTableStore;
